#!python3.2
#-*- coding: utf-8 -*-
"""
Interface to Microsoft Translator API
"""
import urllib.parse
import urllib.request
import codecs
import json

api_translate_url = "http://api.microsofttranslator.com/V2/Ajax.svc/Translate"
api_languages_url = "http://api.microsofttranslator.com/V2/Ajax.svc/GetLanguagesForTranslate"
app_id = ''

class ServiceError(Exception):
    pass

def decode(text):
    if text.startswith(codecs.BOM_UTF8):
        text = text.lstrip(codecs.BOM_UTF8).decode('utf-8')
    elif text.startswith(codecs.BOM_UTF16_LE):
        text = text.lstrip(codecs.BOM_UTF16_LE).decode('utf-16-le')
    elif text.startswith(codecs.BOM_UTF16_BE):
        text = text.lstrip(codecs.BOM_UTF16_BE).decode('utf-16-be')
    return text

def set_app_id(new_app_id):
	global app_id
	app_id = new_app_id

def get_languages():
    sock = urllib.request.urlopen(api_languages_url+'?appid='+app_id)
    result = decode(sock.read())
    result = json.loads(result)
    result.sort()
    return(result)

def _run_query(args):
    """
    takes arguments and optional language argument and runs query on server
    """
    data = urllib.parse.urlencode(args)
    sock = urllib.request.urlopen(api_translate_url + '?' + data)
    result = decode(sock.read())
    if 'Json.Translate' in result and 'Exception' in result:
        raise ServiceError(result)
    return json.loads(result)

def translate(text, source, target, html=False):
    """
    action=opensearch
    """
    if not app_id:
        raise ValueError("AppId needs to be set by set_app_id")
    query_args = {
        'appId': app_id,
        'text': text,
        'from': source,
        'to': target,
        'contentType': 'text/plain' if not html else 'text/html',
        'category': 'general'
    }
    return _run_query(query_args)

if __name__ == '__main__':
    set_app_id('586AEA9498F3CC72E37B88E39D79FD433B671BF8')
    langs = get_languages()
    print(type(langs),langs)
    for lang in ('fr','de','it','es'):
        print(lang)
        for phrase in ('Home','home'):
            print('\tsrc:', phrase)
            print('\ttrg:', translate(phrase,'en',lang))
